﻿using AutoMapper;
using BW.MesProject.BasicData.Domain.基础;
using BW.MesProject.BasicData.Infrastructure;
using BW.MesProject.Public.ErrorCode;
using BW.MesProject.Public.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Yitter.IdGenerator;

namespace BW.MesProject.BasicData.Application
{
    /// <summary>
    /// BOM服务实现类
    /// 提供BOM的增删改查等业务功能
    /// </summary>
    public class BomServices : IBomServices
    {
        private readonly IBaseRepository<Bommodel> bom;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数，通过依赖注入获取仓储和映射器
        /// </summary>
        /// <param name="bom">BOM仓储接口</param>
        /// <param name="mapper">AutoMapper映射器</param>
        public BomServices(IBaseRepository<Bommodel> bom, IMapper mapper)
        {
            this.bom = bom;
            this.mapper = mapper;
        }

        /// <summary>
        /// 添加BOM
        /// </summary>
        public ApiResult<bool> AddBom(Bommodel bommodel)
        {
            try
            {
                // 检查是否已存在相同ID的记录
                if (bommodel.Id > 0)
                {
                    var existingBom = bom.GetValue(b => b.Id == bommodel.Id);
                    if (existingBom != null)
                    {
                        // 如果已存在，执行更新而不是添加
                        return UpdateBom(bommodel);
                    }
                }

                var model = mapper.Map<Bommodel>(bommodel);
                // 如果没有提供ID，则生成新ID，否则保留原ID
                if (model.Id == 0)
                {
                    model.Id = YitIdHelper.NextId();
                }
                model.CreatedTime = DateTime.Now;
                model.IsDeleted = false;
                model.CreatedBy= "admin";
                model.UpdatedTime = DateTime.Now;
                model.UpdatedBy= "admin";

                return new ApiResult<bool>()
                {
                    Code = ApiEnums.Success,
                    Message = "添加成功",
                    Data = bom.Add(model) > 0
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool>()
                {
                    Code = ApiEnums.Error,
                    Message = $"添加失败: {ex.Message}",
                    Data = false
                };
            }
        }

        /// <summary>
        /// 添加子集BOM
        /// </summary>
        public ApiResult<bool> AddChildBom(float parentId, Bommodel childBom)
        {
            // 查找父BOM
            var parentBom = bom.GetValue(b => b.Id == parentId && !b.IsDeleted);
            if (parentBom == null)
            {
                return new ApiResult<bool>()
                {
                    Code = ApiEnums.Fail,
                    Message = "父级BOM不存在",
                    Data = false
                };
            }

            // 设置子BOM的属性
            var model = mapper.Map<Bommodel>(childBom);
            model.Id = YitIdHelper.NextId();
            //父级id转换为long类型
            model.Parentid = Convert.ToInt64(model.Parentid);
            model.CreatedTime = DateTime.Now;
            model.IsDeleted = false;

            model.Bomranks = (1 + 1).ToString();

            return new ApiResult<bool>()
            {
                Code = ApiEnums.Success,
                Message = "添加子集成功",
                Data = bom.Add(model) > 0
            };
        }

        /// <summary>
        /// 根据编码查询BOM
        /// </summary>
        public ApiResult<List<Bommodel>> GetBomsByCode(string? bomCode)
        {
            try
            {
                // 如果没有提供编码，返回所有未删除的BOM
                if (string.IsNullOrEmpty(bomCode))
                {
                    var allBoms = bom.GetAll().Where(b => !b.IsDeleted&&b.Parentid==0).ToList();
                    return new ApiResult<List<Bommodel>>
                    {
                        Code = ApiEnums.Success,
                        Message = "查询成功",
                        Data = allBoms
                    };
                }
                
                // 根据编码精确查询
                var result = bom.GetAll().Where(b => b.Bomcode == bomCode && !b.IsDeleted).ToList();
                
                // 如果精确查询没有结果，尝试模糊查询
                if (result.Count == 0)
                {
                    result = bom.GetAll().Where(b => b.Bomcode.Contains(bomCode) && !b.IsDeleted).ToList();
                }
                
                return new ApiResult<List<Bommodel>>
                {
                    Code = ApiEnums.Success,
                    Message = "查询成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<List<Bommodel>>
                {
                    Code = ApiEnums.Error,
                    Message = $"查询失败：{ex.Message}",
                    Data = new List<Bommodel>()
                };
            }
        }

        /// <summary>
        /// 获取BOM的子集列表
        /// </summary>
        public ApiResult<List<Bommodel>> GetBomDetailWithChildren(long id)
        {
            // 检查父BOM是否存在
            var parentBom = bom.GetValue(x => x.Id == id);
            if (parentBom == null)
            {
                return new ApiResult<List<Bommodel>>()
                {
                    Code = ApiEnums.Fail,
                    Message = "BOM不存在",
                    Data = null
                };
            }

            // 获取子集BOM列表
            var children = bom.GetAll()
                .Where(b => b.Parentid == id && !b.IsDeleted)
                .ToList();

            return new ApiResult<List<Bommodel>>()
            {
                Code = ApiEnums.Success,
                Message = "获取BOM子集成功",
                Data = children,
                TotalCount = children.Count
            };
        }

        /// <summary>
        /// 软删除BOM
        /// </summary>
        public ApiResult<bool> SoftDeleteBom(long id)
        {
            // 查询BOM
            var bomItem = bom.GetValue(b => b.Id == id);
            if (bomItem == null)
            {
                return new ApiResult<bool>()
                {
                    Code = ApiEnums.Fail,
                    Message = "BOM不存在",
                    Data = false
                };
            }

            // 软删除
            bomItem.IsDeleted = true;
            bomItem.UpdatedTime = DateTime.Now;
            bom.Update(bomItem);

            // 递归删除子级BOM
            DeleteChildrenBoms(id);

            return new ApiResult<bool>()
            {
                Code = ApiEnums.Success,
                Message = "删除成功",
                Data = true
            };
        }

        /// <summary>
        /// 递归删除子级BOM
        /// </summary>
        private void DeleteChildrenBoms(long parentId)
        {
            // 获取所有子级BOM
            var childrenBoms = bom.GetAll().Where(b => b.Parentid == parentId).ToList();
            foreach (var child in childrenBoms)
            {
                // 先递归删除子级的子级
                DeleteChildrenBoms(child.Id);

                // 软删除当前子级
                child.IsDeleted = true;
                child.UpdatedTime = DateTime.Now;
                bom.Update(child);
            }
        }

        /// <summary>
        /// 更新BOM信息
        /// </summary>
        public ApiResult<bool> UpdateBom(Bommodel bommodel)
        {
            try
            {
                // 查询现有BOM
                var existingBom = bom.GetValue(b => b.Id == bommodel.Id);
                if (existingBom == null)
                {
                    // 如果不存在，则尝试添加
                    var newModel = mapper.Map<Bommodel>(bommodel);
                    newModel.CreatedTime = DateTime.Now;
                    newModel.IsDeleted = false;
                    newModel.CreatedBy = "admin";
                    newModel.UpdatedTime = DateTime.Now;
                    newModel.UpdatedBy = "admin";
                    
                    return new ApiResult<bool>()
                    {
                        Code = ApiEnums.Success,
                        Message = "记录不存在，已添加新记录",
                        Data = bom.Add(newModel) > 0
                    };
                }

                // 保留不应该被更新的字段
                var createdTime = existingBom.CreatedTime;
                var createdBy = existingBom.CreatedBy;
                var isDeleted = existingBom.IsDeleted;

                // 手动更新属性，不使用AutoMapper
                existingBom.Bomcode = bommodel.Bomcode;
                existingBom.Bomname = bommodel.Bomname;
                existingBom.Bomversion = bommodel.Bomversion;
                existingBom.Productitemid = bommodel.Productitemid;
                existingBom.BomType = bommodel.BomType;
                existingBom.Bomranks = bommodel.Bomranks;
                existingBom.Processmanagementcode = bommodel.Processmanagementcode;
                existingBom.Processmanagementname = bommodel.Processmanagementname;
                existingBom.Bomdosage = bommodel.Bomdosage;
                existingBom.Parentid = bommodel.Parentid;
                existingBom.Bomdescription = bommodel.Bomdescription;
                
                // 更新时间和更新人
                existingBom.UpdatedTime = DateTime.Now;
                existingBom.UpdatedBy = "admin"; // 可以替换为实际的更新用户

                // 恢复不应被修改的字段
                existingBom.CreatedTime = createdTime;
                existingBom.CreatedBy = createdBy;
                existingBom.IsDeleted = isDeleted;

                return new ApiResult<bool>()
                {
                    Code = ApiEnums.Success,
                    Message = "更新成功",
                    Data = bom.Update(existingBom) > 0
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool>()
                {
                    Code = ApiEnums.Error,
                    Message = $"更新失败: {ex.Message}",
                    Data = false
                };
            }
        }
    }
}
